package com.gy.sb.sbfastdfs.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.gy.sb.sbfastdfs.FastDFSClient;

@Controller
public class TestController {
    @Autowired
    public FastFileStorageClient fastFileStorageClient;
    
    
    @RequestMapping(value = {"/img/render"}, method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
    @CrossOrigin(origins = "*")
    @ResponseBody
    public String execute(HttpServletRequest httpServletRequest,
                 HttpServletResponse httpServletResponse) throws IOException {
        
        fastFileStorageClient.downloadFile("group1", "/M00/00/00/wKgBZVvue-WAMIGGAAEiQfgPd08763.jpg", new DownloadCallback<InputStream>() {

            @Override
            public InputStream recv(InputStream ins) throws IOException {
                return ins;
            }
        });
        
        byte[] file_buff = null;
        InputStream inputStream = FastDFSClient.downFile("group1", "/M00/00/00/wKgBZVvue-WAMIGGAAEiQfgPd08763.jpg");
        if(inputStream!=null){
            int len1 = inputStream.available();
            file_buff = new byte[len1];
            inputStream.read(file_buff);
        }
        inputStream.close();
        // img为图片的二进制流
        httpServletResponse.setContentType("image/png");
        OutputStream os = httpServletResponse.getOutputStream();
        os.write(file_buff);
        os.flush();
        os.close();
        return "success";
    }

    @RequestMapping("uploadgo.do")
    @ResponseBody
    public String uploadImg() throws IOException {
        File file = new File("d://documents//space2018//spring-boot//src//main//resources//static//data.jpg");
        try (FileInputStream inputStream = new FileInputStream(file);) {
            String fileName = file.getName();
            String strs = fileName.substring(fileName.lastIndexOf(".") + 1);;
            if (!StringUtils.hasText(strs)) {
                return "fail";
            }
            StorePath storePath = fastFileStorageClient
                    .uploadImageAndCrtThumbImage(inputStream, file.length(),
                            strs, null);
            System.out.println("path------" + storePath.getFullPath());
        }
        return "success";
    }

    @RequestMapping("delete.do")
    @ResponseBody
    public String deleteImg() {
        fastFileStorageClient.deleteFile(
                "group1/M00/00/00/wKgBZVvudnCAVjrfAAEiQfgPd08577.jpg");
        return "success";
    }

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload/go") //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }
        try {
            // Get the file and save it somewhere
            String path=FastDFSClient.saveFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path",
                    "file path url '" + path + "'");
        } catch (Exception e) {
            System.out.println("upload file failed");
            e.printStackTrace();
        }
        return "redirect:/uploadStatus";
    }
    
    @RequestMapping("upload2.do")
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        //File file = new File("d://documents//space2018//spring-boot//src//main//resources//static//data.jpg");
//        try (FileInputStream inputStream = new FileInputStream(file);) {
//            String fileName = file.getName();
//            String strs = fileName.substring(fileName.lastIndexOf(".") + 1);;
//            if (!StringUtils.hasText(strs)) {
//                return "fail";
//            }
//            String path=FastDFSClient.saveFile(file);
//            System.out.println("path------" + path);
//        }
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }
        try {
            // Get the file and save it somewhere
            String path=FastDFSClient.saveFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
            redirectAttributes.addFlashAttribute("path",
                    "file path url '" + path + "'");
        } catch (Exception e) {
            System.out.println("upload file failed");
            e.printStackTrace();
        }
        return "success";
    }

}
